import React, {} from 'react';
import {Button, Input, Card, Form, Checkbox, message} from 'antd';
import type {FormProps} from 'antd';
import {login} from "@/api/users"
import './login.scss'
import {useNavigate} from 'react-router-dom';

type FieldType = {
    email?: string;
    password?: string;
    remember?: string;
};

const Login: React.FC<{ onLogin: () => void }> = ({onLogin}) => {
    const [messageApi, contextHolder] = message.useMessage();
    const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    const navigate = useNavigate();
    const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
        login(values).then(res => {
            if (res.data.token) {
                messageApi.success("登录成功")
                window.localStorage.setItem("token", res.data.token)
                onLogin();
                navigate('/index');
            }
        }).catch(err => {
            messageApi.info(err.data.error)
        })
    };

    return (
        <div className={'login-container'}>
            <div className="water">
            </div>
            <Card className={'login-card'}>
                <div className={'login-card-left'}></div>
                <div className={'login-card-right'}>
                    <h1>Hello,</h1>
                    <h1>Welcome back</h1>
                    <Form
                        name="basic"
                        initialValues={{remember: true}}
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}
                        autoComplete="off"
                    >
                        <Form.Item<FieldType>
                            name="email"
                            rules={[{required: true, message: '请填写邮箱!'}]}
                        >
                            <Input placeholder={'📫：email'}/>
                        </Form.Item>

                        <Form.Item<FieldType>
                            name="password"
                            rules={[{required: true, message: '请填写密码!'}]}
                        >
                            <Input.Password placeholder={'🔑：password'}/>
                        </Form.Item>

                        <Form.Item<FieldType>
                            name="remember"
                            valuePropName="checked"

                        >
                            <Checkbox>Remember me</Checkbox>
                        </Form.Item>

                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                登录
                            </Button>
                        </Form.Item>
                    </Form>
                </div>
            </Card>
            {contextHolder}
        </div>
    );
};

export default Login;
